var dbInfo = {"人口库": "jck_basic_db", "证照库": "fupindb", "法人库": "fupindb", "车辆库": "fupindb"};
var dbConfig = {"ip": "127.0.0.1", "port": "3306", "username": "root", "password": "root", "dbName":""};
var currentSubject = "";
var currentTableName = "";
var currentMeta = [];
var detailTableInit = 0;
var portraitChart = echarts.init(document.getElementById('portrait-chart'));
var tableMap = {};
var mysqlConfig = {
    ip : "127.0.0.1",
    port : "3306",
    dbName : "",
    username : "root",
    password : "root"
};

function init() {
    changeSubject("人口库", "trigger");
}



//切换主体（库）--更新tableName列表
changeSubject = function (item, type) {
    $("#detail-table-div").css("display", 'none');
    $("#portrait-chart-div").css("display","none");
    var subjectName;

    if (type == 'normal') {
        subjectName = $(item).children("input").val();
    }
    else if (type == 'trigger') {
        subjectName = item;
    }

    currentSubject = subjectName;

    $.ajax({
        type: 'GET',
        url: 'search/subject/tables',
        data: {"subject": subjectName},
        cache: false,
        dataType: 'json',
        success:function (data) {
            var tableName = data["tableName"];
            mysqlConfig.tables = tableName;
            mysqlConfig.dbName = dbInfo[currentSubject];

            if (tableName.length > 0) {
                $.ajax({
                    type: 'POST',
                    url: '/MySQLManager/mysql/tables/comments',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(mysqlConfig),
                    async: false,
                    cache: false,
                    dataType: 'json',
                    success: function (resp) {
                        tableMap = Object.assign({}, tableMap, resp.data);

                        var html = "";
                        for (var i = 0; i < tableName.length; i++) {
                            html += '<li>' +
                                '<a onclick="changeTable(this, \'normal\')" value="' + tableName[i] + '">' + tableMap[tableName[i]] + '</a></li>'

                        }
                        $("#table-name-list").empty().append(html);

                        changeTable(tableName[0], "trigger");
                        $("#table-name-list").children().first().addClass('active');

                    }
                })
            }
            else {
                $("#table-name-list").empty();
            }
        }
    });
}

//切换表 --显示表中全部数据，暂未做分页 MARK TODO 分页
changeTable = function (item, type) {
    $("#portrait-chart-div").css("display","none");

    $(item).parent("li").siblings().removeClass("active");
    $(item).parent("li").addClass('active');

    if (detailTableInit == 1) {
        var table = $("#detail-table").DataTable();
        table.destroy();
        $("#detail-table").empty();
    }

    var subjectName = $("[name=portrait-subject]:checked").val();

    var tableName;
    if (type == 'normal') {
        tableName = $(item).attr("value");
    }
    else if (type == 'trigger') {
        tableName = item;
    }

    currentTableName = tableName;

    dbConfig.dbName = dbInfo[subjectName];
    //meta 获得各字段注释
    $.ajax({
        type: 'POST',
        url: '/MySQLManager/mysql/tables/' + tableName + '/comments',
        headers : {
            'Content-Type' : 'application/json'
        },
        data: JSON.stringify(dbConfig),
        async: false,
        cache: false,
        dataType: 'json',
        success: function (resp) {
            var meta = resp.data;
            var columns = [];
            var metaArr = [];
            for (var item in meta) {
                metaArr.push(item);
                if (!(meta[item] == "" || meta[item] == null)) {
                    columns.push({
                        "data": item,
                        "name": item,
                        "title": meta[item]
                    })
                }
            }
            currentMeta = metaArr;

            var dataTableOptions =
                {
                    "columns": columns,
                    "order": [0, "desc"],
                };

            var searchParam = $("#search-label-input").val();
            var dataToSend = {};
            var url = "";
            if (searchParam == "" && searchParam == null) {
                url = 'search/table-data/all';
                dataToSend = {"tableName": tableName, "dbName": dbInfo[subjectName]};
            }
            else {
                url = 'search/table-data/part';
                dataToSend = JSON.stringify({
                    "tableName": currentTableName,
                    "dbName": dbInfo[currentSubject],
                    "meta": currentMeta,
                    "searchParam": searchParam
                });
            }

            //data 获得表格数据
            $.ajax({
                type: 'POST',
                url: url,
                data: dataToSend,
                headers : {
                    'Content-Type' : 'application/json'
                },
                async: false,
                cache: false,
                dataType: 'json',
                success: function (data) {

                    initTable("detail-table", data["data"], dataTableOptions);
                    detailTableInit = 1;
                    $("#detail-table-div").css("display", 'block');
                }
            })
        }
    })

}


searchLabel = function () {
    changeTable(currentTableName, "trigger");
}


$(document).on('click','#detail-table tbody > tr', function () {
    $('#detail-table tbody > tr').css("background-color", "");
    $(this).css("background-color", "#c2e5ff");

    var table = $("#detail-table").DataTable();
    var tbData = table.row(this).data();
    console.log(tbData);
//MARK TO CHANGE



    //获得标签
    $.ajax({
        type: 'GET',
        url: 'search/labels/individual',
        data: {"id": primaryKey, "tableName": currentTableName, "subject": currentSubject},
        cache: false,
        dataType: 'json',
        success: function (data) {
            $("#portrait-chart-div").css("display","block");
            drawPortraitChart(data["labels"]);
        }
    })

});


function initTable(tableName, data, OtherOptions) {
    var options = {
        "destroy": true,
        "bAutoWidth": false,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 20, 50],  //用户可自选每页展示数量
        "iDisplayLength": 20,
        "searching": false,
        "processing": true,
        "ordering": true,
        "data": data,
        "select": {
            style: 'os',
            selector: 'td:first-child'
        },
        "oLanguage": {
            "sProcessing": "正在获取数据，请稍后...",
            "sLengthMenu": "显示 _MENU_ 条",
            "sZeroRecords": "没有找到数据",
            "sInfo": "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",
            "sInfoEmpty": "记录数为0",
            "sInfoFiltered": "(全部记录数 _MAX_ 条)",
            "sInfoPostFix": "",
            "sSearch": "查 询",
            "sUrl": "",
            "oPaginate": {
                "sFirst": "第一页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "最后一页"
            }
        }
    };

    var newOptions = $.extend({}, options, OtherOptions);

    $("#" + tableName).dataTable(newOptions);
}


function drawPortraitChart(data) {

    var symbols = [
        "image://"
    ];
    var count = 1;
    var chartData = [];
    var chartLinks = [];

    chartData.push({
        name: '',
        fixed: false,
        draggable: true, // 是否可以拖拽，默认false
        number: 0, // 这是编号 非必须，目的仅为方便编写line
        symbol : symbols[0],
        symbolSize: [60,160], //图形大小
        value: data,
        itemStyle: {
            normal: {
                color: '#47b9f9',
                borderColor: '#156ACF',
                borderWidth: 1,
                shadowColor: 'rgba(0, 0, 0, 0.4)',
                shadowBlur: 20,
                borderType:'dashed'
            }
        },
    });

    for (var key in data) {
        var source = count;
        chartData.push({
            "name": key,
            "number": count,
            itemStyle: {
                normal: {
                    color: '#dcebff',
                },
            },
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        fontSize: 9,
                        color: '#484b4e'
                    }
                }
            },
            symbol: 'circle',
        });
        chartLinks.push({
            "source": 0,
            "target": count
        });

        count++;

        var arr = data[key];
        for (var i = 0; i < arr.length; i++) {
            chartData.push({
                "name": arr[i] + "(" + key + ")",
                "number": count,
                itemStyle: {
                    normal: {
                        color: '#749dce',
                    }
                },
                symbol: 'rect',
            });
            chartLinks.push({
                "source": source,
                "target": count
            });

            count++;
        }
    }


    var portraitChartOption = {

        tooltip:{
            show:false
        },
        series: [ {
            type: 'graph',
            layout: 'force',
            focusNodeAdjacency: false,
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        fontSize: 12
                    },
                    //color:'auto'
                }
            },
            force: {
                repulsion: 1500
            },
            lineStyle: {
                normal: {
                    opacity: 1,
                    width: 1,
                    curveness: 0.1
                }
            },
            draggable: true,
            symbolSize: function (value, params) {
                return  [params.data.name.length*15,30]
            },
            data: chartData,
            links: chartLinks
        }]
    };

    portraitChart.setOption(portraitChartOption);

    window.addEventListener("resize", function () {
        portraitChart.resize();
    });


}